<script setup>

import {computed, ref, watch} from "vue";
import {getCurMerchant} from "@/api/merchant";
import {getStoreListByMerchantId} from "@/api/store";
import {ElMessageBox} from "element-plus";
import {deletePostById, listPagingPostsByStoreIdWithStoreName, updatePost} from "@/api/merchantPost";
import {Plus} from "@element-plus/icons-vue";

const curMerchant = ref({})
const storeList = ref([]); // 店铺列表
const storeId = ref()
const postsWithStoreName = ref([])
const selectTypes = ref(['全部']);
const total = ref(0)
const pageNo = ref(1)
const pageSize = ref(10)
const selectedPost = ref({})
const drawerVisible = ref(false)
const direction = ref('rtl')

// 获取当前商家信息，然后接着查询商家的店铺
const getCurMerchantInfoWithStores = () => {
  getCurMerchant().then(res => {
    console.info("当前登录的商家信息：", res.data);
    if (res.data) {
      curMerchant.value = res.data
      getStoreListByMerchantId(curMerchant.value.id).then(res => {
        storeList.value = res.data;
      })
    } else {
      ElMessageBox.alert('请先登录商家账号', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        router.push({path: '/merchantLoginPage'})
      })
    }
  })
}
getCurMerchantInfoWithStores()

// 获取贴文列表
const getPosts = () => {
  const query = {
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    storeId: storeId.value,
  };
  listPagingPostsByStoreIdWithStoreName(query).then(res => {
    if (res.data) {
      postsWithStoreName.value = res.data.records
      total.value = res.data.total
    }
  })
};
getPosts();

// 页码改变
const pageNoChange = (value) => {
  //value就是页码
  pageNo.value = value
  getPosts();
}
//页大小改变
const pageSizeChange = (value) => {
  pageSize.value = value
  getPosts();
}

// ------------帖子类别选择---------------
const isAllChecked = ref(true);
const isNewProductChecked = ref(false);
const isSeasonalChecked = ref(false);
const isDiscountChecked = ref(false);
const isOthersChecked = ref(false);
const isAnnouncementChecked = ref(false);
const isExclusiveChecked = ref(false);

const handleAllChange = (status) => {
  isAllChecked.value = status;
  // 如果选中全部，取消其他所有选项
  if (status) {
    isNewProductChecked.value = false;
    isSeasonalChecked.value = false;
    isDiscountChecked.value = false;
    isOthersChecked.value = false;
    isExclusiveChecked.value = false;
    isAnnouncementChecked.value = false;
  }
  updateCheckedTags();
};
const handleNewProductChange = (status) => {
  if (status) isAllChecked.value = false;
  isNewProductChecked.value = status;
  updateCheckedTags();
};
const handleSeasonalChange = (status) => {
  if (status) isAllChecked.value = false;
  isSeasonalChecked.value = status;
  updateCheckedTags();
};
const handleDiscountChange = (status) => {
  if (status) isAllChecked.value = false;
  isDiscountChecked.value = status;
  updateCheckedTags();
};
const handleAnnouncementChange = (status) => {
  if (status) isAllChecked.value = false;
  isAnnouncementChecked.value = status;
  updateCheckedTags();
};
const handleOthersChange = (status) => {
  if (status) isAllChecked.value = false;
  isOthersChecked.value = status;
  updateCheckedTags();
};
const handleExclusiveChange = (status) => {
  if (status) isAllChecked.value = false;
  isExclusiveChecked.value = status;
  updateCheckedTags();
};
const checkedTags = ref([])
const updateCheckedTags = () => {
  checkedTags.value = [];
  if (isNewProductChecked.value) checkedTags.value.push('新品上新');
  if (isSeasonalChecked.value) checkedTags.value.push('季节限定');
  if (isDiscountChecked.value) checkedTags.value.push('促销活动');
  if (isOthersChecked.value) checkedTags.value.push('其他');
  if (isExclusiveChecked.value) checkedTags.value.push('粉丝福利');
  if (isAnnouncementChecked.value) checkedTags.value.push('店铺公告');
};

const posts = computed(() => {
  if (checkedTags.value.length === 0) return postsWithStoreName.value;
  return postsWithStoreName.value.filter(post => {
    if (!post.postType) return false;
    return checkedTags.value.includes(post.postType);
  });
});


// 删除贴文
const removePosts = (row) => {
  ElMessageBox.confirm('是否确定删除该贴文？', '提示').then(() => {
    deletePostById(row.id).then(res => {
      if (res.data) {
        getPosts(); // 刷新列表
        ElMessageBox.alert('删除成功', '提示', {
          confirmButtonText: '确定',
          type: 'success'
        }).then(() => {
        });
      }
    });
  })
      .catch(() => {
        // 取消删除操作
      });
};

// 编辑贴文
const editPosts = (row) => {
  selectedPost.value = JSON.parse(JSON.stringify(row))
  drawerVisible.value = true
}

// 上传图片
const handleMediaSuccess = (res) => {
  selectedPost.value.mediaUrls.push(res.data.url)
  console.log(selectedPost.value.mediaUrls)
}

// 保存修改的贴文
const onSubmit = () => {
  if (!selectedPost.value.title || !selectedPost.value.contentText) {
    ElMessageBox.alert('请填写完整的贴文信息', '提示', {
      confirmButtonText: '确定',
      type: 'warning'
    });
    return;
  }
  const updatedPost = {
    id: selectedPost.value.id,
    postType: selectedPost.value.postType,
    title: selectedPost.value.title,
    contentText: selectedPost.value.contentText,
    // mediaUrls: selectedPost.value.mediaUrls,
    visibility: selectedPost.value.visibility,
  };
  updatePost(updatedPost).then(res => {
    if (res.data) {
      ElMessageBox.alert('贴文修改成功', '提示', {
        confirmButtonText: '确定',
        type: 'success'
      }).then(() => {
        drawerVisible.value = false; // 关闭抽屉
        getPosts(); // 刷新列表
      });
    } else {
      ElMessageBox.alert('贴文修改失败，请稍后再试', '提示', {
        confirmButtonText: '确定',
        type: 'error'
      });
    }
  }).catch(err => {
    console.error("修改贴文时发生错误：", err);
    ElMessageBox.alert('贴文修改失败，请稍后再试', '提示', {
      confirmButtonText: '确定',
      type: 'error'
    });
  })
}

// 取消编辑
const cancelClick = () => {
  drawerVisible.value = false
  getPosts();
}

</script>

<template>
  <el-card>
    <div class="filter-container">
      <span class="filter-label">筛选条件：</span>
      <div class="checkbox">
        <!--类型筛选-->
        <el-check-tag
            type="primary"
            :checked="isAllChecked"
            @change="handleAllChange"
            class="type-tag"
        >
          全部
        </el-check-tag>
        <el-check-tag
            type="primary"
            :checked="isNewProductChecked"
            @change="handleNewProductChange"
            class="type-tag"
        >
          新品介绍
        </el-check-tag>
        <el-check-tag
            type="primary"
            :checked="isSeasonalChecked"
            @change="handleSeasonalChange"
            class="type-tag"
        >
          季节限定
        </el-check-tag>
        <el-check-tag
            type="primary"
            :checked="isDiscountChecked"
            @change="handleDiscountChange"
            class="type-tag"
        >
          促销活动
        </el-check-tag>
        <el-check-tag
            type="primary"
            :checked="isExclusiveChecked"
            @change="handleExclusiveChange"
            class="type-tag"
        >
          粉丝福利
        </el-check-tag>
        <el-check-tag
            type="primary"
            :checked="isAnnouncementChecked"
            @change="handleAnnouncementChange"
            class="type-tag"
        >
          店铺公告
        </el-check-tag>
        <el-check-tag
            type="primary"
            :checked="isOthersChecked"
            @change="handleOthersChange"
            class="type-tag"
        >
          其他
        </el-check-tag>
      </div>
      <el-select
          style="margin-left: auto; width: 300px"
          v-model="storeId"
          placeholder="请选择店铺"
          clearable
          @change="getPosts"
      >
        <el-option
            v-for="store in storeList"
            :label="store.name"
            :value="store.id"
        />
      </el-select>
    </div>
    <el-table :data="posts" style="width: 100%" stripe>
      <el-table-column
          prop="stores[0].name"
          label="店铺名称"
          header-align="center"
          align="center"
      />
      <el-table-column
          prop="postType"
          label="贴文类别"
          header-align="center"
          align="center"
      />
      <el-table-column
          prop="title"
          label="标题"
          header-align="center"
          align="center"
      />
      <el-table-column
          prop="contentText"
          label="内容"
          header-align="center"
          align="center"
      >
        <template #default="scope">
                <span :title="scope.row.contentText">
                    {{
                    scope.row.contentText.length > 20 ? scope.row.contentText.substring(0, 20) + '...' : scope.row.contentText
                  }}
                </span>
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          header-align="center"
          align="center"
      >
        <template #default="scope">
          <!--      scope.row表示该行数据    -->
          <el-button type="primary" @click="editPosts(scope.row)">编辑</el-button>
          <el-button type="danger" @click="removePosts(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="pageSizeChange"
        @current-change="pageNoChange"
    />


    <!--  贴文编辑抽屉  -->
    <el-drawer
        v-model="drawerVisible"
        :direction="direction"
        :size="'50%'"
    >
      <template #header>
        <h4>编辑贴文</h4>
      </template>
      <template #default>
        <span>
          <el-form>
            <el-form-item label="贴文标题">
              <el-input v-model="selectedPost.title"/>
            </el-form-item>
            <el-form-item label="贴文内容">
              <el-input v-model="selectedPost.contentText" type="textarea" :rows="10"/>
            </el-form-item>
            <el-form-item label="贴文图片">
              <el-image
                  v-for="(url, idx) in selectedPost.mediaUrls"
                  :key="idx"
                  :src="url"
                  class="medias"
                  style="margin-right: 10px; height: 100px"
                  fit="cover"
              />
              <el-upload
                  class="store-photos-uploader"
                  action="/api/file/upload"
                  :show-file-list="false"
                  :on-success="(res, file) => handleMediaSuccess(res, file)"
              >
                <el-icon class="avatar-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="贴文类型">
              <el-radio-group v-model="selectedPost.postType">
                <el-radio-button label="店铺公告" value="店铺公告"/>
                <el-radio-button label="新品介绍" value="新品介绍"/>
                <el-radio-button label="促销活动" value="促销活动"/>
                <el-radio-button label="季节限定" value="季节限定"/>
                <el-radio-button label="粉丝福利" value="粉丝福利"/>
                <el-radio-button label="其他" value="其他"/>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="可见范围">
              <el-switch
                  v-model="selectedPost.visibility"
                  class="mb-2"
                  style="--el-switch-on-color: #16c564; --el-switch-off-color: #419fff"
                  active-text="仅粉丝可见"
                  inactive-text="公开"
                  active-value="仅粉丝可见"
                  inactive-value="公开"
              />
            </el-form-item>
          </el-form>
        </span>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>

<style scoped lang="scss">
.filter-container {
  display: flex;
  align-items: center;
  height: 40px;
  margin-bottom: 16px;

  .filter-label {
    margin-right: 10px;
    font-size: 14px;
    color: #606266;
  }

  .checkbox {
    display: flex;
    align-items: center;
  }
}
</style>